<script lang="ts" setup>
import {userLoginApi} from "@/api/user"
import {computed, onMounted, ref, watch} from "vue"
import {checkLogin} from "@/utils/verify"
import {getCaptchaApi, submitVerifyApi, verifyUserApi} from "@/api/verfiy"
import type {VerifyUserResponse} from "@/types/loginVerfiy"
import {useUserStore} from "@/stores/user";
import {IMessage} from "@/components/aw-message/message";
import {useCountStore} from "@/stores/count";
import {onShow} from "@dcloudio/uni-app";
// 登录信息
const loginInfo = ref<{
  username: string,
  password: string,
}>({} as { username: string, password: string })

onShow(() => {
  if (countStore.timeRemaining < 60) {
    countStore.start()
  }
})
// 注册
const checkPassword = ref() // 二次密码
const popup = ref()
const isRegister = ref(false) // 用户是否选择注册
const onRegister = () => {
  isRegister.value = !isRegister.value
}
// 点击确认
const confirmRegister = () => {
  popup.value
}

// 点击登录
const isShowVerify = ref(false)
const verifyData = ref<VerifyUserResponse>()
const checkAgreement = ref(false) //  是否同意协议
const checkUserStatus = async () => {
  // 发送前校验
  const checkResult = checkLogin(loginInfo.value.username, loginInfo.value.password)
  if (checkResult !== true) {
    return uni.showToast({
      title: checkResult,
      icon: "none"
    })
  }
  const res = await verifyUserApi()
  isShowVerify.value = true
  verifyData.value = res.data
}
// 选择图片
const chooseImgs = ref<number[]>()

const onChooseImg = (index: number) => {
  if (chooseImgs.value?.includes(index)) {
    chooseImgs.value = chooseImgs.value?.filter(item => item !== index)
    return
  }
  if (chooseImgs.value) {
    chooseImgs.value.push(index)
    return
  }
  chooseImgs.value = [index]
}

const onBeforeLogin = async () => {
  if (!chooseImgs.value) {
    return
  }
  const res = await submitVerifyApi(chooseImgs.value)
  if (res.code === '0') {
    return uni.showToast({
      title: res.message,
      icon: 'error',
      mask: true
    })
  }

  // 校验通过
  isShowVerify.value = false
  await onLogin()
}

// 关闭
const onCloseVerify = () => {
  isShowVerify.value = false
}

/**
 *get the captcha when the page is displayed
 */
onMounted(() => {
  getCode()
})
const codeSrc = ref() // the captcha image source
const code = ref() //captcha
let codeChangeCount = 0
let timer: number | null = null
let timeRemaining = 60
const codeId = ref()
const countStore = useCountStore()
const delay = ref(false)
/**
 * get the captcha
 */
const getCode = async () => {
  if (countStore.waitCode) {
    return uni.showToast({title: `请稍后重试获取验证码`, icon: 'none'})
  }
  if (delay.value) {
    return
  }
  delay.value = true
  /*  if (countStore.timer) {
      console.log('Count:', countStore.codeCount)
      return uni.showToast({title: `请${countStore.timeRemaining}s后重试获取验证码`, icon: 'none'})
    }*/
  getCaptchaApi().then(res => {
    codeSrc.value = "data:image/png;base64, " + res.data.base64Image
    codeId.value = res.data.id
  })
      .catch(e => {
        console.log('e:', e)
        countStore.waitCode = true
        countStore.start()
        console.log('waitCode-true:', countStore.waitCode)
        return uni.showToast({title: `请${countStore.timeRemaining}s后重试获取验证码`, icon: 'none'})
      }).finally(() => {
    delay.value = false
  })

}

/**
 * When user login
 */
const onLogin = async () => {
  if (!checkAgreement.value) {
    return uni.showToast({title: '请先同意用户协议', icon: 'none'})
  }

  uni.showLoading({title: '登录中'})
  if (isRegister.value) {
    if (checkPassword.value !== loginInfo.value.password) {
      return uni.showToast({title: '两次密码输入不一致', icon: 'none'})
    }
  }

  //Verify the captcha before login
  if (code.value === undefined) {
    return uni.showToast({title: '请输入验证码', icon: 'none'})
  } else if (code.value.length !== 4) {
    return uni.showToast({title: '请输入正确的验证码', icon: 'none'})
  }
  const res = await userLoginApi(loginInfo.value, code.value, codeId.value)
  uni.hideLoading()
  if (res.code === '0') {
    await getCode()
    code.value = ''
    return uni.showToast({
      title: res.message,
      icon: 'none'
    })
  }
  // 登陆成功
  const userStore = useUserStore()
  userStore.userInfoData = res.data
  userStore.userInfoData.avatarURL = userStore.userInfoData.avatarURL
      ? userStore.userInfoData.avatarURL
      : '/static/kun.png'
// 获取当前平台
  const platform = uni.getSystemInfoSync().uniPlatform
  if (platform === 'app' || platform === 'web') {
    IMessage({
      content: '登录成功',
      type: 'success',
      showIcon: true,
    })
  }
// #ifdef MP-WEIXIN
  uni.showToast({title: '登录成功', icon: 'success'})
// #endif
  setTimeout(() => {
    uni.navigateBack()
  }, 500)
}
const showPassword = ref(true)
const showSecondPassword = ref(true)
const goAgreement = () => {
  uni.navigateTo({
    url: '/subPkg/agreement/agreement'
  })
}
const onCheckBoxChange = (e: any) => {
}

/**
 * 用户找回密码
 */
const handleFindBack = () => {
  uni.navigateTo({
        url: '/subPkg/login/findBackPw/findBackPw'
      }
  )
}

const changeListener = computed(() => {
  return loginInfo.value.username && loginInfo.value.password && code.value && checkAgreement.value
})
// 校验用户输入
const checkUserInput = ref(false)
watch(changeListener, (newValue) => {
  if (loginInfo.value.username !== '' && loginInfo.value.password !== '' && code.value !== '' && checkAgreement.value) {
    if (isRegister.value) {
      checkUserInput.value = checkPassword.value === loginInfo.value.password
    } else {
      checkUserInput.value = true
    }
  } else {
    checkUserInput.value = false
  }
})
</script>

<template>
  <view class="login-container">
    <view class="login-title focus-in-expand"> mccute</view>
    <view class="login-box">
      <!--      <image class="logo" mode="aspectFit" src="/static/logo.png"></image>-->

      <view class="title">{{ isRegister ? "注册" : "登录" }}</view>
      <view class="login-form">
        <!-- 表单内容 -->
        <view class="form-item">
          <text class="cuIcon-my line-awGreen margin-right-lg margin-left-xs" style="font-size: 24px"></text>
          <input v-model="loginInfo.username" :maxlength="15" class="input" placeholder="用户名" type="text"/>
        </view>
        <view class="form-item">
          <text class="cuIcon-lock line-awGreen margin-right-lg margin-left-xs" style="font-size: 24px"></text>
          <input v-model="loginInfo.password" :maxlength="20" :password="showPassword" class="input" placeholder="密码"
                 type="safe-password"/>
          <uv-icon :name="showPassword?'eye-off-outline':'eye'" color="#999" size="26"
                   @click="showPassword=!showPassword"></uv-icon>
        </view>
        <view v-if="isRegister" class="form-item" style="position:relative;">
          <text v-show="loginInfo.password!==checkPassword" class="text-red text-sm"
                style="position:absolute;bottom: 10px;left: 5px">两次密码不一致
          </text>
          <text class="cuIcon-lock line-awGreen margin-right-lg margin-left-xs" style="font-size: 24px"></text>
          <input v-model="checkPassword" :maxlength="20" :password="showSecondPassword" class="input"
                 placeholder="确认密码"
                 type="safe-password"/>
          <uv-icon :name="showPassword?'eye-off-outline':'eye'" color="#999" size="26"
                   @click="showSecondPassword=!showSecondPassword"></uv-icon>
        </view>
        <view class="form-item">
          <text class="cuIcon-safe line-awGreen margin-right-lg margin-left-xs" style="font-size: 24px"></text>
          <input v-model="code" :maxlength="4" class="input" placeholder="请输入验证码" type="safe-password"/>
          <image v-if="codeSrc" :src="codeSrc" class="login-img" mode="aspectFit" style="width: 340px;height: 50px" @click="getCode">
          </image>
          <view v-if="countStore.waitCode" class="text-gray">{{ countStore.timeRemaining }}s</view>
          <text v-if="!codeSrc" class="text-gray" style="width: 80px" @click="getCode">获取</text>
        </view>
        <view class="flex justify-between" style="width: 100%">
          <view class="text-awGreen text-lg" @click="onRegister">{{ !isRegister ? "注册" : "登录" }}</view>
          <view class="text-gray" @click="handleFindBack">忘记密码?</view>
        </view>

      </view>
      <view :class="['login-btn',checkUserInput?'login-btn-active':'login-btn-disabled']"
            :hover-class="{'hover-btn':checkUserInput}" type="default" @click="/*checkUserStatus*/onLogin">
        {{ isRegister ? "注册并登录" : "登录" }}
      </view>
      <view class="text-gray flex align-center" style="font-size: 12px;margin-top: 10px">
        <checkbox :checked="checkAgreement" style="transform:scale(0.7)" @change="onCheckBoxChange"
                  @click="checkAgreement=!checkAgreement"/>
        登录即视为您阅读并同意
        <text class="text-blue" @click="goAgreement">《用户协议及隐私政策》</text>
      </view>
    </view>
  </view>
  <!--  弹框-->
  <uni-popup ref="popup" type="dialog">
    <uni-popup-dialog :showClose="false" cancel-text="取消" confirm-text="确认"
                      content="系统会自动根据用户名判断，如第一次登录将自动注册"
                      title="提示" type="info" @confirm="confirmRegister"></uni-popup-dialog>
  </uni-popup>

  <!--  &lt;!&ndash; 验证 &ndash;&gt;
    <view v-if="isShowVerify" class="verify">
      <image mode="aspectFit" src="/static/cancel.png"
             style="position: absolute; top: 10px; right: 10px; width: 30px; height: 30px;" @click="onCloseVerify"/>
      <view>请根据问题选择正确的选项：</view>
      <view class="verify-q">{{ verifyData?.question }}</view>
      <view class="verify-a">
        <view v-for="(item, index) in verifyData?.imgs" :key="index" style="position: relative;">
          <image v-if="chooseImgs?.includes(index)" class="check-img" mode="scaleToFill" src="/static/verify-check.png"/>
          <image :src="item" class="verify-img" mode="aspectFill" @click="onChooseImg(index)"/>
        </view>
      </view>
      <button class="verify-btn" hover-class="button-hover" type="default" @click="onBeforeLogin">提交
      </button>
    </view>-->
</template>


<style lang="scss" scoped>
// 文字动画
.focus-in-expand {
  animation: focus-in-expand 1s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

@keyframes focus-in-expand {
  0% {
    letter-spacing: -0.5em;
    filter: blur(12px);
    opacity: 0;
  }
  100% {
    filter: blur(0px);
    opacity: 1;
  }
}

.login-container {
  width: 100vw;
  height: 100vh;
  min-height: 800px;
  background: #06beb6;
  /* fallback for old browsers */
  background: linear-gradient(to right, #06beb6, #48b1bf);
  position: relative;

  .login-title {
    color: #39c5bb;
    font-size: 90rpx;
    font-weight: bold;
    position: absolute;
    top: 8%;
    left: 50%;
    transform: translate(-50%, -50%);
    // 文字阴影突起效果
    text-shadow: 0 0 4px rgba(150, 150, 150, 1);
  }

  .login-box {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    top: 19%;
    background: rgb(255, 255, 255);
    /* fallback for old browsers */
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
    border-radius: 30px 30px 0 0;
    display: flex;
    align-items: center;
    flex-direction: column;
    padding-top: 15%;

    .logo {
      width: 30%;
      height: 30%;
      position: absolute;
      left: 50%;
      top: 0;
      transform: translate(-50%, -50%);
    }

    // 标题样式
    .title {
      font-size: 28px;
      font-weight: bold;
      margin-bottom: 20px;
      color: #39c5bb;
    }

    // 表单
    .login-form {
      background-color: #fff;
      width: 80%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      border-radius: 20px;
      padding-top: 10px;
      margin-bottom: 40px;
      position: relative;
      padding-bottom: 20px;

      .form-item {
        display: flex;
        justify-content: space-around;
        align-items: center;
        margin-bottom: 10px;
        border-bottom: #39c5bb 1px solid;
        width: 93%;

        .login-img {
          width: 42rpx;
          height: 42rpx;
          margin-right: 20rpx;
        }

        .input {
          width: 80%;
          height: 70px;
        }
      }
    }

    // 按钮
    .login-btn {
      width: 70%;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: visible;
      border: none;
      position: relative;
      font-size: 21px;
      z-index: 9;
      border-radius: 25px;

      /*      &::before {
              content: "";
              position: absolute;
              width: 60px;
              height: 100%;
              top: 0;
              left: 0;
              bottom: 0;
              transform: translateX(-50%);
              border-radius: 50%;
              background-color: #39c5bb;
              z-index: 1;
            }

            &::after {
              content: "";
              position: absolute;
              width: 60px;
              height: 100%;
              top: 0;
              right: 0;
              bottom: 0;
              transform: translateX(50%);
              border-radius: 50%;
              background-color: #39c5bb;
              z-index: 1;
            }*/
    }

    .login-btn-active {
      background-color: #39c5bb;
      color: #fff;
    }

    .login-btn-disabled {
      background: #E4E5E7FF;
      color: #98999CFF !important;
    }

    .hover-btn {
      background-color: rgb(46, 155, 146);

      &::before,
      &::after {
        background-color: rgb(46, 155, 146);
      }
    }
  }

  .tip {
    color: #39c5bb;
    font-size: 14px;
    position: absolute;
    bottom: 20px;
    left: 20px;
  }
}

.verify {
  position: absolute;
  top: 60%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  //height: 40%;
  background-color: #f1f1f1;
  border-radius: 20px;
  color: #39c5bb;
  font-size: 16px;
  line-height: 40px;
  text-align: center;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding-left: 10px;
  padding-right: 10px;

  .verify-a {
    width: 100%;
    height: 250px;
    display: grid;
    // 两行四列，图片撑满容器
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(2, 1fr);
    // 图片大小
    grid-auto-rows: 100px;
    grid-auto-columns: 100px;
    position: relative;

    .verify-img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .check-img {
      width: 30px;
      height: 30px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      z-index: 99999;
    }
  }

  .verify-btn {
    width: 100%;
    height: 50px;
    background-color: #39c5bb;
    border-radius: 25px;
    margin-top: 20px;
    color: #f1f1f1;
  }
}
</style>
